import {Component, OnInit} from '@angular/core';
import {Account} from "../account";
import {Router, ActivatedRoute} from "@angular/router";
import {AccountsService} from "../accounts.service";
import {ResponseUtil} from "../../../../util/response-util";
import {PageSubject} from "../../../../util/page-subject";
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {MsgResult} from "../../../../models/msg-result";
import {FormGroup, Validators, FormBuilder} from "@angular/forms";
import {MsgConstants} from "../../../../constants/constants";

@Component({
  selector: 'app-account-add',
  templateUrl: './account-add.component.html'
})
export class AccountAddComponent implements OnInit {

  //声明实例
  account: Account;

  id: string;

  accountId: string;

  accountForm: FormGroup;

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private fb: FormBuilder,
    private responseUtil: ResponseUtil,
    private pageSubject: PageSubject,
    private dialogService: OneDialogService,
    private accountsService: AccountsService
  ) {
    this.initObject();
  }

  ngOnInit() {
    this.pushPage();
    if (!!this.route.snapshot.params["accId"]) {
      this.accountId = this.route.snapshot.params["accId"];
      this.initAccountAddForm(this.accountId);
    }
  }

  /**
   * 面包屑导航
   */
  private pushPage() {
    let path = new Path("权限系统", "");
    this.pageSubject.pushPage("账户管理", "新增", path);
  }


  /**
   * 构造表单
   */
  buildForm(): void {
    this.accountForm = this.fb.group({
      'id': [this.account.id],
      'accountName': [this.account.accountName, [
        Validators.required,
        Validators.minLength(6),
        Validators.maxLength(16),
        Validators.pattern(/^[A-Za-z0-9_]+$/)
      ]],
      'password': [this.account.password, [
        Validators.required,
        Validators.minLength(6),
        Validators.maxLength(20),
        Validators.pattern(/^[A-Za-z0-9_.]+$/)
      ]],
      'confirmPassword': [this.account.confirmPassword, [
        Validators.required,
        Validators.minLength(6),
        Validators.maxLength(20),
        Validators.pattern(/^[A-Za-z0-9_.]+$/)
      ]],
      'isEnable': [this.account.isEnable, [
        Validators.required,
        Validators.maxLength(1)
      ]],
      'isAudit': [this.account.isAudit, [
        Validators.required,
        Validators.maxLength(1)
      ]],
      'isAllowPc': [this.account.isAllowPc, [
        Validators.required,
        Validators.maxLength(1)
      ]],
      'isAllowApp': [this.account.isAllowApp, [
        Validators.required,
        Validators.maxLength(1)
      ]]
    });

    this.accountForm.valueChanges.subscribe(
      data => this.onValueChanged(data)
    );
    this.onValueChanged();
  }
  /**
   * 值变化监听
   * @param data
   */
  onValueChanged(data?: any) {
    if (!this.accountForm) {
      return;
    }
    const form = this.accountForm;
    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
    this.confirmPassword(); //验证密码
  }
  /**
   * 验证密码
   */
  confirmPassword(){
    let confirmPwdCtrl = this.accountForm.get('confirmPassword');
    confirmPwdCtrl.valueChanges.subscribe(
      data => this.onConfirmPwdValueChanged(data)
    );
  }
  onConfirmPwdValueChanged(data){
    this.account = this.accountForm.value;
    console.log(this.account);
    if (this.account.password != data) {
      this.accountForm.get('confirmPassword').setErrors({"notUnique":"设置密码与确认密码不一致"});
      this.formErrors.confirmPassword = "设置密码与确认密码不一致";
    }
  }
  /**
   * 校验字段
   * @type {{name: string; code: string}}
   */
  formErrors = {
    'accountName': '',
    'password': '',
    'confirmPassword': '',
    'isEnable': '',
    'isAudit': '',
    'isAllowPc': '',
    'isAllowApp': '',
  };

  /**
   * 校验提示信息
   * @type {{name: {required: string; maxlength: string}; code: {required: string; maxlength: string; pattern: string}}}
   */
  validationMessages = {
    'accountName': {
      'required': '账户名不能为空',
      'minlength': '长度不能低于6',
      'maxlength': '长度不能超过16',
      'pattern': '只能由字母、数字、下划线组成'
    },
    'password': {
      'required': '密码不能为空',
      'minlength': '长度不能少于6',
      'maxlength': '长度不能超过20',
      'pattern': '只能由字母、数字、下划线、点组成'
    },
    'confirmPassword': {
      'required': '确认密码不能为空',
      'minlength': '长度不能少于6',
      'maxlength': '长度不能超过20',
      'pattern': '只能由字母、数字、下划线、点组成',
      "notUnique":"设置密码与确认密码不一致"
    }
  };


  /**
   * 添加账户
   */
  onSubmit() {
    this.account = this.accountForm.value;
    if (this.account.password == this.account.confirmPassword) {
      this.accountsService.insertAccount(this.account).subscribe(
        result => this.responseUtil.success(result, this.processResult),
        message => this.responseUtil.error(message)
      );
    }
  }

  /**
   *  获取添加信息
   * @param json
   */
  private processResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.successWithCancelBtn("添加成功，是否继续添加？", () => this.initObject(), () => this.cancelAccountAdd());
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 为账户分配角色
   */
  assignRolesForAccount() {
    this.account = this.accountForm.value;
    if (this.account.password == this.account.confirmPassword) {
      this.accountsService.insertAccount(this.account).subscribe(
        result => this.responseUtil.success(result, this.processAccountAssignRoleResult),
        message => this.responseUtil.error(message)
      );
    } else {
      this.dialogService.successWithCancelBtn("设置密码与确认密码不一致！", () => this.initObject());
    }
  }

  /**
   *  获取新增账户信息
   * @param result
   */
  private processAccountAssignRoleResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.assignRole(result);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message, () => this.initObject());
    }
  }

  /**
   * 跳转到分配角色页面
   * @param result : 添加成功后的返回值
   */
  private assignRole(result) {
    this.router.navigate(['../assign', {accountId: result.data.id}], {relativeTo: this.route});
  }

  /**
   * 取消添加
   */
  cancelAccountAdd() {
    this.router.navigate(['..'], {relativeTo: this.route});
  }

  /**
   * 由分配角色上一步时，初始化
   * @param id
   */
  private initAccountAddForm(id) {
    this.accountsService.getAccountById(id).subscribe(
      result => this.responseUtil.success(result, this.processAccountDataResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   * 获取初始化表单数据
   * @param result
   */
  private processAccountDataResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.account = result.data;
      this.account.password = " ";
      this.accountForm.patchValue(this.account);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message, () => this.initObject());
    }
  }

  /**
   * 实例化对象
   */
  private initObject() {
    this.account = new Account("", "", "", "", "", "", "", "", "", "0", "0", "0", "0", "0");
    this.buildForm();
  }

}
